package com.autumn.platform.core.spring;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class CacheManagerAspect {

    private String cacheNamePrefix;

    public String getCacheNamePrefix() {
        return cacheNamePrefix;
    }

    public void setCacheNamePrefix(String cacheNamePrefix) {
        this.cacheNamePrefix = cacheNamePrefix;
    }

    @Around("execution(public * org.springframework.cache.CacheManager.getCache(..)) && args(name) ")
    public Object aroundGetCache(ProceedingJoinPoint point, String name) throws Throwable {
        if (null != this.cacheNamePrefix) {
            return point.proceed(new Object[] {cacheNamePrefix + name});
        }
        return point.proceed();
    }

    @Around("execution(public * org.springframework.cache.CacheManager.getCacheNames())")
    public Object aroundGetCacheNames(ProceedingJoinPoint point) throws Throwable {
        if (null != this.cacheNamePrefix) {
            @SuppressWarnings("unchecked")
            Collection<String> cacheNames = (Collection<String>) point.proceed();
            if (null != cacheNames && !cacheNames.isEmpty()) {
                List<String> names = new ArrayList<String>(cacheNames.size());
                for (String cacheName : cacheNames) {
                    names.add(cacheName.substring(cacheNamePrefix.length()));
                }
                return Collections.unmodifiableList(names);
            } else {
                return cacheNames;
            }
        }
        return point.proceed();
    }
}
